<template>
  <div class="weight-record-card">
    <div class="weight-header">
      体重记录
      <button class="weight-add-btn" @click="showForm = true">+</button>
    </div>
    <div class="weight-chart-placeholder">
      <div ref="chartRef" style="width:100%;height:220px;"></div>
    </div>
    <div class="weight-recent">最近记录：{{ recentWeight }} kg</div>
    <el-dialog v-model="showForm" title="手动添加体重记录" width="400px">
      <el-form :model="form" @submit.prevent="submit">
        <el-form-item label="体重(kg)">
          <el-input v-model.number="form.weight" type="number"/>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker v-model="form.date" type="date" placeholder="选择日期"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.note"/>
        </el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import dayjs from 'dayjs'

const showForm = ref(false)
const form = ref({ weight: '', date: '', note: '' })
const records = ref([])
const recentWeight = ref('--')
const chartRef = ref(null)
let chartInstance = null

const submit = async () => {
  if (form.value.date) {
    form.value.date = dayjs(form.value.date).format('YYYY-MM-DD')
  }
  await request.post('/sport/weight/', form.value)
  showForm.value = false
  await fetchRecords()
}

const fetchRecords = async () => {
  const res = await request.get('/sport/weight/')
  // 按日期升序排列
  const sorted = res.sort((a, b) => new Date(a.date) - new Date(b.date))
  records.value = sorted
  if (sorted && sorted.length > 0) {
    recentWeight.value = sorted[sorted.length - 1].weight
  } else {
    recentWeight.value = '--'
  }
  renderChart()
}

const renderChart = () => {
  if (!chartRef.value) return
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }
  const weights = records.value.map(r => r.weight)
  if (!weights.length) return
  const minWeight = Math.min(...weights)
  const maxWeight = Math.max(...weights)
  let padding = Math.max(1, Math.ceil((maxWeight - minWeight) * 0.15)) // 15%区间
  if (maxWeight === minWeight) padding = 2
  let yMin = Math.floor(minWeight - padding)
  let yMax = Math.ceil(maxWeight + padding)
  if (yMin > minWeight - 1) yMin = minWeight - 1
  if (yMin < 0) yMin = 0

  const option = {
    grid: { left: 72, right: 16, top: 24, bottom: 32 },
    xAxis: {
      type: 'category',
      data: records.value.map(r => r.date),
      axisLabel: { rotate: 30, interval: 'auto' }
    },
    yAxis: {
      type: 'value',
      min: yMin,
      max: yMax,
      splitNumber: 5,
      axisLabel: {
        fontSize: 14,
        formatter: function(value) {
          return value + ' kg'
        }
      }
    },
    dataZoom: [{ type: 'slider', start: 0, end: 100 }],
    series: [{
      data: weights,
      type: 'line',
      smooth: true,
      areaStyle: {}
    }],
    tooltip: { trigger: 'axis' }
  }
  chartInstance.setOption(option)
}

onMounted(() => {
  fetchRecords()
  window.addEventListener('resize', () => {
    chartInstance && chartInstance.resize()
  })
})

watch(records, renderChart)
</script>

<style scoped>
.weight-record-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(114,46,209,0.08);
  padding: 20px 24px;
  min-height: 220px;
  display: flex;
  flex-direction: column;
  margin-bottom: 8px;
}
.weight-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 17px;
  color: #722ed1;
  font-weight: bold;
  margin-bottom: 10px;
}
.weight-add-btn {
  background: #f3e6ff;
  color: #722ed1;
  border: none;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  font-size: 20px;
  font-weight: bold;
  cursor: pointer;
}
.weight-chart-placeholder {
  width: 100%;
  height: 220px;
  background: #f3e6ff;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #aaa;
  font-size: 15px;
  margin-bottom: 8px;
  padding-left: 8px;
  box-sizing: border-box;
}
.weight-recent {
  font-size: 14px;
  color: #888;
}
</style> 